package fr.dbManager.pierop.com;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import fr.myExceptions.pierop.com.DBManagerSingletonException;
import fr.myExceptions.pierop.com.databaseDriverException;
import fr.myExceptions.pierop.com.databaseUrlException;

public class DBManager {

	private String		driver = null;
	private String		database = null;
	private String		user = null;
	private String		pass = null;
	
	private Connection	con;
	private Statement	state;
	
	private DatabaseMetaData	dbMeta;
	
	private static DBManager	singletonObject = null;
	
	private DBManager (String driver, String database, String user, String pass) {
		this.driver = driver;
		this.database = database;
		this.user = user;
		this.pass = pass;
	}
	
	public static DBManager getInstance(String driver, String database, String user, String pass)
	{
		if (DBManager.singletonObject == null)
			DBManager.singletonObject = new DBManager(driver, database, user, pass);
		return DBManager.singletonObject;
	}
	
	public static DBManager getInstance() throws DBManagerSingletonException
	{
		if (DBManager.singletonObject == null)
			throw new DBManagerSingletonException();
		return DBManager.singletonObject;
	}
	
	public void connection(boolean verbose) throws Exception {
		try {
			Class.forName(this.driver);
			this.con = DriverManager.getConnection(this.database, this.user, this.pass);
			this.state = this.con.createStatement();
		}
		catch (java.lang.ClassNotFoundException e) { throw new databaseDriverException(); }
		catch (java.sql.SQLException e) { throw new databaseUrlException(); }
		catch (Exception e) { throw e; }
		this.dbMeta = this.con.getMetaData();
		if (verbose) { this.printInfos(); }
	}	
		
	public void disconnection() {
		try { this.con.close(); } catch (SQLException e) { e.printStackTrace(); }
	}

	public void update(String query) throws SQLException {
		if (query != null) this.state.executeUpdate(query);
	}
	
	public ResultSet execute(String query) throws SQLException {
		if (query != null)
		{
			ResultSet 	 r = this.state.executeQuery(query);
			return r;
		}
		else
			return null;
	}
	
	private	void printInfos() throws SQLException{
		System.out.println("\nConnexion reussie a la base de donnee.");
		System.out.println("	Utilisateur : " + this.dbMeta.getUserName());
		System.out.println("	Serveur : " + this.dbMeta.getDatabaseProductName());
		System.out.println("	Driver : " + this.dbMeta.getDriverName());
	}
}
